package Part6_动态性;

import org.junit.Test;

import javax.xml.crypto.Data;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * ClassName: Demo
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.04.28 0:16
 */
public class ReflectionTest {
    public Person getInstance(){
        return new Person();
    }

    //一、体现反射的动态性：根据传入字符串的方式决定创建哪个类的对象
    public <T> T getInstance(String className) throws Exception {
        Class<?> aClass = Class.forName(className);
        Constructor<?> constructor = aClass.getDeclaredConstructor();

        constructor.setAccessible(true);

        return (T) constructor.newInstance();
    }

    @Test
    public void test1() throws Exception {
        Person person = getInstance("Part6_动态性.Person");
        System.out.println(person);

        Date date = getInstance("java.util.Date");
        System.out.println(date);
    }

    //二、体现反射的动态性：根据传入字符串的方式决定创建哪个类的对象
    public Object invoke(String className, String methodName) throws Exception {
        //1、创建对象
        Class<?> aClass = Class.forName(className);
        Constructor<?> constructor = aClass.getDeclaredConstructor();
        constructor.setAccessible(true);

        Object object = constructor.newInstance();

        //2、获取运行时类指定的方法
        Method method = aClass.getDeclaredMethod(methodName);
        method.setAccessible(true);

        return method.invoke(object);
    }

    @Test
    public void test2() throws Exception {
        String className = "Part6_动态性.Person";
        String methodName = "showAge";

        Object invoke = invoke(className, methodName);//age = 0
        System.out.println(invoke);//null:因为返回值是void


    }
}
